package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/go-sql-driver/mysql"
	"net/http"
)

func HandleErrors() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			//自定义错误处理
			if c.Errors != nil {
				c.JSON(http.StatusBadRequest, gin.H{
					"code": 400,
					"msg":  "自定义错误, " + c.Errors.String(),
				})
				return
			}
			//错误处理
			if err := recover(); err != nil {
				var (
					errMsg     string
					mysqlError *mysql.MySQLError
					ok         bool
				)
				if errMsg, ok = err.(string); ok {
					c.JSON(http.StatusInternalServerError, gin.H{
						"code": 500,
						"msg":  "system error, " + errMsg,
					})
					return
				} else if mysqlError, ok = err.(*mysql.MySQLError); ok {
					c.JSON(http.StatusInternalServerError, gin.H{
						"code": 500,
						"msg":  "system error, " + mysqlError.Error(),
					})
					return
				} else {
					c.JSON(http.StatusInternalServerError, gin.H{
						"code": 500,
						"msg":  err,
					})
					return
				}
			}
		}()
		c.Next()
	}
}
